package com.webapp.services;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.webapp.DTO.Articles;
import com.webapp.DTO.Comments;
import com.webapp.DTO.Users;
import com.webapp.beans.Article;
import com.webapp.beans.CommentsData;
import com.webapp.interfaces.IArticleService;
import com.webapp.utils.HibernateUtil;

@Service
public class ArticleService implements IArticleService{

	
	public Articles getContent(int id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		String query = "FROM Articles as art WHERE art.arId = :id";
		Query q = session.createQuery(query);
		q.setParameter("id", id);
		List<Articles> data = q.list();
		session.getTransaction().commit();
		Articles da = null;
		if(data.size()>0){
			da = data.get(0);
		}
		
		return da;
	}

	public List<CommentsData> getComments(int id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		String query = "FROM Comments as com WHERE com.articlesArId = :id";
		Query q = session.createQuery(query);
		q.setParameter("id", id);
		List list = q.list();
		List<CommentsData> dataComments = new ArrayList<CommentsData>();
		for(Object i : list){
			Comments com = (Comments)i;
			dataComments.add(new CommentsData(com.getUserName(), com.getCmComment(),com.getCmId()));
			
		}
		session.getTransaction().commit();
		return dataComments;
	}

	public void addArticle(Articles article) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(article);
		session.getTransaction().commit();
		
	}
	
	public Users getUserData(String login){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		String q = "FROM Users as us where us.usLogin = :login";
		Query query = session.createQuery(q);
		query.setParameter("login", login);
		List<Users> data = (List<Users>)query.list();
		session.getTransaction().commit();
		return data.get(0);
	}

	public void addComment(CommentsData comment) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Comments comm = new Comments();
		comm.setCmComment(comment.getContent());
		comm.setUserName(comment.getLogin());
		comm.setUsersUsId(1);
		comm.setArticlesArId(comment.getId());
		session.beginTransaction();
		session.save(comm);
		session.getTransaction().commit();
		
		
	}

}
